package minidb.drive;

import minidb.record.*;
import static minidb.type.Const.*;
public class TableScanner
{
	private String tableName;
	private TableInfo tab;
	private RecordPage rec;
	
	public TableScanner(String tableName){
		this.tableName = tableName;
		tab = tablePage.get(tableName);
		while(true){
			synchronized(tab.lock){
				if(tab.ID < 0 || Thread.currentThread().getId() == tab.ID)
					break;
			}
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		rec = new RecordPage(tab);
	}
	
	public Tuple GetTupleByRid(String ridStr)
	{
		RID r = new RID(ridStr);
		Record record = rec.get(r);
		if(record == null)
			return null;
		return new Tuple(record, tableName);
	}
	
	public void Rewind(){
		rec.rewind();
	}
	
	public Tuple Next(){	
		if(!rec.next())
			return null;
		Record record = rec.get();
		if(record == null)
			return null;
		return new Tuple(record, tableName);
	}
	
	public Tuple NextRid(){
		if(!rec.next())
			return null;
		return new Tuple(rec.getRid());
	}
}
